//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#ifndef __ELASTOS_CSDETECT_H__
#define __ELASTOS_CSDETECT_H__

#include <elatypes.h>
#include <eladef.h>
#include <elapi.h>
#include <spinlock.h>

#ifdef CRITICAL_SECTION_DEADLOCK_DETECT

extern SpinLock g_csSpinlock;

EXTERN void CSDeadLockDetection(CriticalSection *pCurCS, int nCurThreadID);

EXTERN void InsertIntoCSList(CriticalSection *pCS);

EXTERN void InsertIntoCSWaitList(CriticalSection *pCS, int nThreadID);

EXTERN void DetachFromCSList(CriticalSection *pCS);

EXTERN void DetachFromCSWaitList(CriticalSection *pCS, int nThreadID);

EXTERN void InitCSDetection();

//#define CSDETECT_INSERT_INTO_CSLIST InsertIntoCSList(&m_sect);

#define CSDETECT_INSERT_INTO_CSWAITLIST \
    { \
        g_csSpinlock.Lock(); \
        InsertIntoCSWaitList(this, id); \
        g_csSpinlock.Unlock(); \
    }

#define CSDETECT_DETACH_FROM_CSLIST \
    { \
        g_csSpinlock.Lock(); \
        DetachFromCSList(this); \
        g_csSpinlock.Unlock(); \
    }

#define CSDETECT_DETACH_FROM_CSWAITLIST \
    { \
        g_csSpinlock.Lock(); \
        DetachFromCSWaitList(this, id); \
        g_csSpinlock.Unlock(); \
    }

#define CSDETECT_DEADLOCK_DETECTION \
    { \
        g_csSpinlock.Lock(); \
        CSDeadLockDetection(this, id); \
        g_csSpinlock.Unlock(); \
    }

#define CSDETECT_INIT InitCSDetection();

#else

//#define CSDETECT_INSERT_INTO_CSLIST

#define CSDETECT_INSERT_INTO_CSWAITLIST

#define CSDETECT_DETACH_FROM_CSLIST

#define CSDETECT_DETACH_FROM_CSWAITLIST

#define CSDETECT_DEADLOCK_DETECTION

#define CSDETECT_INIT

#ifdef MULTI_RESOURCE_DEADLOCK_DETECT

extern SpinLock g_csSpinlock;

EXTERN void InitMultiResourceDeadLock();

EXTERN void InsertOwnerList(int nThreadID, _ELASTOS CRITICAL_SECTION *pCS);

EXTERN void DetachFromOwnerList(int nThreadID, _ELASTOS CRITICAL_SECTION *pCS);

#define MULTI_RESOURCE_DEADLOCK_INIT InitMultiResourceDeadLock();

#define INSERT_OWNERLIST \
    { \
            g_csSpinlock.Lock(); \
            InsertOwnerList(id, this); \
            g_csSpinlock.Unlock(); \
    }

#define DETACH_FROMOWNERLIST \
    { \
            g_csSpinlock.Lock(); \
            DetachFromOwnerList(id, this); \
            g_csSpinlock.Unlock(); \
    }
#endif //MULTI_RESOURCE_DEADLOCK_DETECT

#endif //CRITICAL_SECTION_DEADLOCK_DETECT

#endif //__ELASTOS_CSDETECT_H__
